package com.wongleoi.weather_demo.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import com.wongleoi.weather_demo.*
import com.wongleoi.weather_demo.data.Result
import com.wongleoi.weather_demo.databinding.WeatherDetailBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flowOn

/**

 * @author wongleoi

 * @classname WeatherDetailFragment.kt

 * @describe  城市天气详情

 * @time 2022/7/15 17:13

 */
class WeatherDetailFragment : Fragment() {
    private val mViewModel by activityViewModels<WeatherViewModel>()

    //navigation传递的参数
    private val args: WeatherDetailFragmentArgs by navArgs()
    private var mLayoutManager: LinearLayoutManager? = null
    private lateinit var pagingAdapter: CityWeatherDetailAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.weather_detail, container, false)

    lateinit var viewBinding: WeatherDetailBinding
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinding = WeatherDetailBinding.bind(view).apply {
            mLayoutManager = LinearLayoutManager(WeatherApplication.getContext())
            pagingAdapter =
                CityWeatherDetailAdapter(mutableListOf(), WeatherApplication.getContext())
            recyclerView.run {
                layoutManager = mLayoutManager
                adapter = pagingAdapter
            }
        }
        weatherInfo()
    }


    /**
     * 获取城市天气预报
     */
    private fun weatherInfo() {
        if (isDetached || !isAdded || activity == null) return
        //北京：110000,上海：310000
        mViewModel.weatherInfo(
            MainConst.AMAPKEY,
            args.city.adcode,
            MainConst.EXTENSIONS,
            MainConst.OUTOUT
        )
            .flowOn(
                Dispatchers.IO
            ).asLiveData()
            .observe(viewLifecycleOwner) {
                mViewModel.loading.value = false
                when (it) {
                    is Result.Error -> {
                        Toast.makeText(requireContext(), "", Toast.LENGTH_SHORT).show()
                    }
                    is Result.Success -> {
                        val weatherInfo = it.data.first()
                        viewBinding.apply {
                            tvCity.text = weatherInfo.city
                            tvPublishTime.text =
                                StringBuffer().append(getString(R.string.string_publish_time))
                                    .append(weatherInfo.reporttime)
                            tvForecastPublishTime.text =
                                StringBuffer().append(getString(R.string.string_publish_time))
                                    .append(weatherInfo.reporttime)
                            tvDayweather.text = weatherInfo.casts[0].dayweather
                            tvDaytemp.text =
                                StringBuffer().append("气温:").append(weatherInfo.casts[0].daytemp).append("℃")
                            tvDaywind.text =
                                StringBuffer().append(weatherInfo.casts[0].daywind).append("   ")
                                    .append(weatherInfo.casts[0].daypower).append("级")
                        }
                        pagingAdapter.apply {
                            val start = adapterData.size
                            adapterData.addAll(weatherInfo.casts)
                            notifyItemRangeInserted(start, weatherInfo.casts.size)
                        }
                    }
                }
            }
    }

}